package com.beans;

import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import model.User;

import com.Constants;
import com.factory.Util;
import com.services.UserService;
import com.sun.corba.se.impl.orbutil.closure.Constant;

//see faces-config.xml to see annotations

public class RegisterBean {
	@EJB
	UserService service;

	private String name;
	private String password;
	private String passwordRepeat;

	public String getPasswordRepeat() {
		return passwordRepeat;
	}

	public void setPasswordRepeat(final String passwordRepeat) {
		this.passwordRepeat = passwordRepeat;
	}

	public String getName() {
		return name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(final String password) {
		this.password = password;
	}

	public void register() throws NoSuchAlgorithmException {
		// if (!validateUserInput()) return;
		// TODO: check for existing user with same username
		User newUser = new User();
		newUser.setPassword(Util.getPasswordHash(password));
		newUser.setUserName(name);
		// only users
		newUser.setRole(Constants.USER);

		service.createUser(newUser);
	}

	private boolean validateUserInput() {
		boolean uNameValid = validateUserName();
		if (!uNameValid) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Invalid Username!", "Please Try Again!"));
			return false;
		}
		boolean repeatedPassword = validatePasswordRepeated();
		if (!repeatedPassword) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Passwords must match!", "Please Try Again!"));
			return false;
		}
		boolean passValid = validatePassword();
		if (!passValid) {
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Password must be in correct format!",
							"Please Try Again!"));
			return false;
		}
		return true;
	}

	//

	private boolean validatePassword() {
		Pattern p = Pattern
				.compile("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s).{4,8}$");
		Matcher m = p.matcher(this.password);
		return m.matches();
	}

	private boolean validatePasswordRepeated() {
		return password.equals(passwordRepeat);
	}

	private boolean validateUserName() {
		Pattern p = Pattern.compile("[a-zA-Z0-9]\\w*");
		Matcher m = p.matcher(this.name);
		return m.matches();
	}
}
